// User Selenium extension
// @Author Jiayan
//

Selenium.prototype.myGetAttribute=function(attributeLocator){
   var result = this.browserbot.myFindAttribute(attributeLocator);
   return result;
}
Selenium.prototype.parentWithAttributeValue=function(elem,attribute,value){
	if (!elem){ return false; }
		var parent = elem;
		while (parent){
			if (parent.getAttribute(attribute) == value){
				return parent; 
			}
			parent = parent.parentNode;
		}
		return false;
	}
Selenium.prototype.parentWithAttribute=function(elem,attribute){
	if (!elem){ return false; }
		var parent = elem;
		while (parent){
			if (parent.getAttribute(attribute)){
				return parent; 
			}
			parent = parent.parentNode;
		}
		return false;
	}
Selenium.prototype.attributeValueFindParent=function(elem,attribute){
		var parent=this.parentWithAttribute(elem,attribute);
		if (parent){
			return parent.getAttribute(attribute);
		}else{
			return false;
		}
	}

Selenium.prototype.findWidgetbyId = function(widgetId){
		//var ctls=this.browserbot.getCurrentWindow().inforsense.gadgets.serviceinstance.controllers;
		var ctls=this.browserbot.getCurrentWindow().inforsense.gadgets.serviceInstance.form.Controllers.list;
		for(var c in ctls){
			if (ctls[c].getWidget) {
				w=ctls[c].getWidget(widgetId);
				if (w){
					return w;
				}
			}
		}
		return null;
}

Selenium.prototype.findRenderer=function(locator,caption){
	 var element = this.browserbot.findElement(locator);
	 var form=this.browserbot.getCurrentWindow().inforsense.utils.dom.parentWithTag(this.browserbot.findElement(locator),"FORM");
	 //var mgr=this.browserbot.getCurrentWindow().inforsense.gadgets.serviceinstance.mgr.get(form);
	 var mgr=this.browserbot.getCurrentWindow().inforsense.gadgets.serviceInstance.form.Controllers.get(form);
	 
	 return mgr.getRendererByCaption(caption);
}

Selenium.prototype.storeRenderer=function(locator,caption,variableName){
	storedVars[variableName] = this.findRenderer(locator,caption);
}

Selenium.prototype.storeWidget=function(locator,caption,widgetName,variableName){
	var renderer=this.findRenderer(locator,caption);
	storedVars[variableName] =renderer.getWidgetByName(widgetName);;
}

Selenium.prototype.storeWidgetById=function(widgetId,variableName){
	 storedVars[variableName] =this.findWidgetbyId(widgetId); 
}

Selenium.prototype.clearStored=function(variableName){
	storedVars[variableName] =null;
}

Selenium.prototype.isExpectedResult=function(variableName,expression,expectValue){
	if (this.getExpressionResult(variableName,expression)==expectValue){
		return true;
	}else{
		return false;
	}
}
Selenium.prototype.getExpressionResult=function(variableName,expression){
	return eval("storedVars[\""+variableName+"\"]."+expression);
}

Selenium.prototype.isJsObjectPresent=function(variableName){
	if(storedVars[variableName]){
		return true;
	}else{
		return false;
	}
}

Selenium.prototype.getSelectedRowsInPage=function(variableName){
	 var tableWidget=storedVars[variableName];
	 return tableWidget.getSelectedRowsInPage();
	 
}

Selenium.prototype.selectRowInTable=function(variableName,row){
	 var tableWidget=storedVars[variableName];
	 tableWidget.setSelection(rows);
}


Selenium.prototype.selectGadgetTableRowInTableByClickDom=function(gadgetId,row){
	var row=this.browserbot.findElement("//div[@id='"+gadgetId+"']"+"//div[contains(@class,'x-grid3-row')]["+row+"]")
	if(row){
		storedVars["rowElement"]=row;
		this.doMouseDownAt("domobject=storedVars['rowElement']","1,1");
		storedVars["rowElement"]=null;
	 }
}



Selenium.prototype.selectRowInTableByClickDom=function(widgetId,row){
	var row=this.browserbot.findElement("//span[@widgetid='"+widgetId+"']"+"//div[contains(@class,'x-grid3-row')]["+row+"]")
	if(row){
		storedVars["rowElement"]=row;
		this.doMouseDownAt("domobject=storedVars['rowElement']","1,1");
		storedVars["rowElement"]=null;
	 }
}

Selenium.prototype.getSelectedRowsInPageByXPath=function(widgetId){
	var rows=this.xpath("//span[@widgetid='"+widgetId+"']"+"//div[contains(@class,'x-grid3-row')]")
	var returnIndexs=[];
	
	if(rows && (rows instanceof Array || typeof rows == "array")){
			for(var i=0;i<rows.length;i++){
				var row=rows[i];
				if (row.className.indexOf("x-grid3-row-selected")>0 ){
					returnIndexs.push(i+1);
				}				
		}
		return 	returnIndexs;
	 }
}



Selenium.prototype.getGadgetTableSelectedRowsInPageByXPath=function(gadgetId){
	var rows=this.xpath("//div[@id='"+gadgetId+"']"+"//div[contains(@class,'x-grid3-row')]")
	var returnIndexs=[];
	
	if(rows && (rows instanceof Array || typeof rows == "array")){
			for(var i=0;i<rows.length;i++){
				var row=rows[i];
				if (row.className.indexOf("x-grid3-row-selected")>0 ){
					returnIndexs.push(i+1);
				}				
		}
		return 	returnIndexs;
	 }
}

Selenium.prototype.xpath=function(xpath,dom){
	// HUGE hack - remove namespace from xpath for IE
	dom=dom||this.browserbot. getCurrentWindow().document;
    if (browserVersion.isIE) {
        xpath = xpath.replace(/x:/g, '')
    }

    // Use document.evaluate() if it's available
    if (this.allowNativeXpath && dom.evaluate) {
        return inDocument.evaluate(xpath, dom, this._namespaceResolver, 0, null).iterateNext();
    }

    // If not, fall back to slower JavaScript implementation
    // DGF set xpathdebug = true (using getEval, if you like) to turn on JS XPath debugging
    //xpathdebug = true;
    var context = new ExprContext(dom);
    var xpathObj = xpathParse(xpath);
    var xpathResult = xpathObj.evaluate(context);
    if (xpathResult && xpathResult.value) {
        return xpathResult.value;
    }
    return null;
}

Selenium.prototype.doSliderMove = function(locator, selectionAreaString) {
	this.doChartSelection(locator, selectionAreaString, false);
}

Selenium.prototype.doChartSelection = function(locator, selectionAreaString, isDelay) {
    /** Drags an element a certain distance and then drops it
    * @param locator an element locator
    * @param selectionAreaString  indicate the selection area , format: beginX,beginY,endX,endY
    */
    var element = this.browserbot.findElement(locator);
    var clientStartXY = getClientXY(element)
    var clientStartX = clientStartXY[0];
    var clientStartY = clientStartXY[1];
    
    var selectionArea = selectionAreaString.split(/,/);
	
	var beginX = Number(selectionArea[0]);
    var beginY = Number(selectionArea[1]);
	
	clientStartX=clientStartX+beginX;
	clientStartY=clientStartY+beginY;
    var clientFinishX = clientStartX+Number(selectionArea[2]);
    var clientFinishY = clientStartY+Number(selectionArea[3]);
    
//    var clientFinishX = ((clientStartX + movementX) < 0) ? 0 : (clientStartX + movementX);
//   var clientFinishY = ((clientStartY + movementY) < 0) ? 0 : (clientStartY + movementY);
    
    var mouseSpeed = this.mouseSpeed;
    var move = function(current, dest) {
        if (current == dest) return current;
        if (Math.abs(current - dest) < mouseSpeed) return dest;
        return (current < dest) ? current + mouseSpeed : current - mouseSpeed;
    }
    
    this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientStartX, clientStartY);
    this.browserbot.triggerMouseEvent(element, 'mousemove',   true, clientStartX, clientStartY);
    var clientX = clientStartX;
    var clientY = clientStartY;
    
    while ((clientX != clientFinishX) || (clientY != clientFinishY)) {
        clientX = move(clientX, clientFinishX);
        clientY = move(clientY, clientFinishY);
        this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientX, clientY);
    }
    
    this.browserbot.triggerMouseEvent(element, 'mousemove',   true, clientFinishX, clientFinishY);
    if(isDelay) {
    	setTimeout(function() {selenium.browserbot.triggerMouseEvent(element, 'mouseup',   true, clientFinishX, clientFinishY)}, 500);
    } else {
    	selenium.browserbot.triggerMouseEvent(element, 'mouseup',   true, clientFinishX, clientFinishY);
    }
	
};



/**
 * Finds an element using by evaluating the specfied string.
 */
PageBot.prototype.locateElementByDomObject = function(domTraversal, document, window) {
	
    var browserbot = this.browserbot;
    var element = null;
    try {
        element = eval(domTraversal);
    } catch (e) {
        return null;
    }

    if (!element) {
        return null;
    }

    return element;
};
PageBot.prototype.locateElementByDomObject.prefix = "domobject";

PageBot.prototype.myFindAttribute = function(locator) {
    // Split into locator + attributeName
    var attributePos = locator.lastIndexOf("@");
    var elementLocator = locator.slice(0, attributePos);
    var attributeName = locator.slice(attributePos + 1);

    // Find the element.
    var element = this.findElement(elementLocator);

    // Handle missing "class" attribute in IE.
    if (browserVersion.isIE && attributeName == "class") {
        attributeName = "className";
    }

    // Get the attribute value.
    var attributeValue = element.getAttribute(attributeName);
	//original code in selenium
   // return attributeValue ? attributeValue.toString() : null;
   return attributeValue;
};